import { applyDecorators, UseInterceptors } from '@nestjs/common'
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express'
import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface'

/**
 * 封装文件类型过滤
 * @param {string[]} type 类型
 * @returns
 */
export function fileFilter(type: string[]) {
  return (req: any, file: Express.Multer.File, callback: (error: Error | null, acceptFile: boolean) => void) => {
    const check = type.some((t) => file.mimetype.includes(t))
    if (!check) {
      callback(new Error('文件类型错误'), false)
    } else {
      callback(null, true)
    }
  }
}

/**
 * 上传文件装饰器
 * @param {string} filed 字段名称
 * @param {MulterOptions} options 上传配置
 * @returns
 */
export function LvUpload(filed: string = 'file', options?: MulterOptions) {
  return applyDecorators(UseInterceptors(FileInterceptor(filed, options)))
}

/**
 * @param {string} field 上传字段
 * @param {string[]} type 文件类型
 * @param {number} fileSize 文件大小
 * @returns
 */
export function LvUploadFile(field: string = 'file', type: string[] = ['image'], fileSize: number = 3) {
  return LvUpload(field, {
    limits: { fieldSize: Math.pow(1024, 2) * fileSize },
    fileFilter: fileFilter(type),
  })
}

/**
 * 多文件上传装饰器
 * @param {string} filed
 * @param {number} maxCount
 * @param {MulterOptions} options
 * @returns
 */
export function LvUploads(filed: string = 'files', maxCount: number = 6, options?: MulterOptions) {
  return applyDecorators(UseInterceptors(FilesInterceptor(filed, maxCount, options)))
}

/**
 *
 * @param {string} filed
 * @param {number} maxCount
 * @param {string[]} type
 * @param {number} fileSize
 * @returns
 */
export function LvUploadFiles(
  filed: string = 'files',
  maxCount: number = 6,
  type: string[] = ['image'],
  fileSize: number = 3,
) {
  return LvUploads(filed, maxCount, {
    limits: { fieldSize: Math.pow(1024, 2) * fileSize },
    fileFilter: fileFilter(type),
  })
}
